// storeListen.ts
class StoreListen {
    old = {} as Record<string, any>
    timer = 0 as any
    constructor() {
        this.old = this.getAllSore()
    }
    getAllSore() {
        const keys = Object.keys(localStorage)
        return Object.fromEntries(keys.map(key => [key, localStorage.getItem(key)]))
    }
    start() {
        this.stop()
        this.timer = setInterval(() => {
            const newStore = this.getAllSore()
            const difKeys: string[] = []
            const { old } = this
            Object.entries(newStore).forEach(([k, v]) => {
                const newV = typeof v === 'object' ? JSON.stringify(v) : v + ''
                const oldV = typeof old[k] === 'object' ? JSON.stringify(old[k]) : old[k] + ''
                if (newV !== oldV) difKeys.push(k)
            })
            this.old = newStore
            if (difKeys.length) {
                window.dispatchEvent(new CustomEvent('localStoreChange', { detail: difKeys }))
            }
        }, 300)
    }
    stop() {
        clearInterval(this.timer)
    }
}
export default new StoreListen()


// main.ts
import { createApp } from 'vue'
import './style.css'
import App from './App.vue'
import StoreListen from './StoreListen'

createApp(App).mount('#app')

StoreListen
window.addEventListener('visibilitychange', () => {
    if (document.visibilityState === 'hidden') {
        // 当页面变为不可见时执行的操作
        console.log('页面已隐藏')
        StoreListen.start()
        // 这里可以进行节省资源或其他处理逻辑
    } else if (document.visibilityState === 'visible') {
        // 当页面重新变为可见时执行的操作
        console.log('页面已显示')
        StoreListen.stop()

        // 这里可以恢复之前的状态或执行更新逻辑
    }
})

// .vue文件使用
type LocalStoreChange = {
    detail: string[]
}
window.addEventListener('localStoreChange', (e) => {
    console.error('我是自定义时间', (e as any as LocalStoreChange).detail)
    const { detail } = e as any as { detail: string[] }
    if (detail.includes('a')) {
        console.log('我改刷新了')
    }
})
